package com.example.demo.controller;

import com.example.demo.pojo.Article;
import com.example.demo.pojo.R;
import com.example.demo.service.ArticleService;
import com.example.demo.util.IdThreadLocal;
import com.example.demo.util.MinioUtil;
import com.example.demo.util.TokenUtil;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
@CrossOrigin
@RestController
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private MinioUtil minioUtil;
    @Value("${minio.articleUrl}")
    private String articleUrl;



    @GetMapping("/getArticle")
    public R  getArticle( ){
        List<Article> list = articleService.list();
        return R.success(list);
    }




    @PostMapping("uploadArticle")
    public R uploadArticle(@RequestParam("file") MultipartFile file , @RequestParam("legendName")String legendName , HttpServletRequest request,@RequestParam("description")String description ,@RequestParam("articleName")String articleName  ){
        Article article=new Article();
        String Name=file.getOriginalFilename();
        String[] split = Name.split("\\.");
        article.setArticleName(articleName);
        article.setDescription(description);
        article.setLegendName(legendName);
        Integer plaerId=tokenUtil.verify(request.getHeader("Token"));
        System.out.println(IdThreadLocal.get());
        article.setAuthorId(plaerId);
        article.setArticleUrl(articleUrl+legendName+"/"+articleName+"."+split[1]);
        System.out.println(article);
        minioUtil.uploadFile(file,"article",legendName+"/"+articleName);
        articleService.save(article);
        return R.success("上传成功");
    }
}
